<?php
/**
 * 支付回调
 *
 *
 *
 *
 * @copyright  Copyright (c) 2007-2013 BesonIT Inc. (http://www.besonit.com)
 * @license    http://www.besonit.com
 * @link       http://www.besonit.com
 * @since      File available since Release v1.1
 */


defined('BYshopJL') or exit('Access Invalid!');

class paymentControl extends wxHomeControl
{

    private $payment_code;

    public function __construct()
    {
        parent::__construct();

        $this->payment_code = $_GET['payment_code'];
    }

    /**
     * 支付回调
     */
    public function returnOp()
    {
        unset($_GET['act']);
        unset($_GET['op']);
        unset($_GET['payment_code']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getReturnInfo($payment_config);

        if ($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if ($result['state']) {
                Tpl::output('result', 'success');
                Tpl::output('message', '支付成功');
            } else {
                Tpl::output('result', 'fail');
                Tpl::output('message', '支付失败');
            }
        } else {
            //验证失败
            Tpl::output('result', 'fail');
            Tpl::output('message', '支付失败');
        }

        Tpl::showpage('payment_message');
    }

    /**
     * 支付提醒
     */
    public function notifyOp()
    {


        // 恢复框架编码的post值
        $_POST['notify_data'] = html_entity_decode($_POST['notify_data']);

        $payment_api = $this->_get_payment_api();

        $payment_config = $this->_get_payment_config();

        $callback_info = $payment_api->getNotifyInfo($payment_config);

        if ($callback_info) {
            //验证成功
            $result = $this->_update_order($callback_info['out_trade_no'], $callback_info['trade_no']);
            if ($result['state']) {
                //发送微信消息提示
                /*  $type:
                    1=>'新订单通知',
                    2=>'发货通知（发给买家--货到付款）',
                    3=>'发货通知',
            $wxSdk->TemplateId($type);

                $tp:
                    1=>'新订单通知买家',
                    2=>'新订单通知买家货到付款',
                    3=>'新订单通知卖家',
                    4=>'新订单通知卖家(货到付款)',
                    5=>'发货通知（发给买家--货到付款）',
                    6=>'发货通知，发给买家',
                    7=>'发货通知，发给卖家',
            $wxSdk->setTemplateData($tp,$data);
            */
                require_once(BASE_ROOT_PATH.'/weixin/framework/libraries/wxSdk.class.php');
                $wxSdk = new wxSdk();
                $model_order = Model('order');
                $wxSdk->TemplateId(1)->TemplateUrl(0)->setTemplateTopColor();
                $map['pay_sn'] = array('eq',$callback_info['out_trade_no']);
                $new_order = $model_order->getOrderInfo($map,array('order_common','order_goods','store'));
                //循环产品发送消息
                foreach($new_order['extend_order_goods'] as $vv){
                    $data = array(
                        'goods_name' =>$vv['goods_name'],
                        'goods_pay_price' =>$vv['goods_pay_price'],
                        'goods_num' =>$vv['goods_num'],
                        'profit' =>$vv['profit']//抵扣红包
                    );
                    $wxSdk->Touser(array('member_id'=>$vv['buyer_id']));
                    $wxSdk->setTemplateData(1,$data);//新订单通知买家
                    $wxSdk->sendTemplateMessage();

                    //新订单发给卖家
                    $wxSdk->Touser(array('member_id'=>$new_order['extend_store']['member_id']));
                    $wxSdk->setTemplateData(3,$data);
                    $wxSdk->sendTemplateMessage();

                }
                echo 'success';
                die;
            }
        }

        //验证失败
        echo "fail";
        die;
    }

    public function wxnotifyOp()
    {
        include_once(API_PATH . "/payment/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $Notify = new Notify_pub();

        //接收微信推送过来的数据 xml
        $xml = '';
        $Notify->saveData($GLOBALS['HTTP_RAW_POST_DATA']);

        //file_put_contents('Notify.txt',var_export($Notify,true));

        //验证sign
        if ($Notify->checkSign() && $Notify->data['return_code'] && $Notify->data['result_code']) {

            $order_pay_info = Model('wx_order')->getOrderPayInfo(array('pay_sn' => $Notify->data['out_trade_no']));
            //file_put_contents('order_pay_info.txt',var_export($order_pay_info,true));
            if ($order_pay_info['api_pay_state'] != 1) {
                $result = $this->_update_order($Notify->data['out_trade_no'], $Notify->data['transaction_id']);

                //file_put_contents('result.txt',var_export($result,true));
                if ($result['state']) {
                    //发送微信消息提示
                    /*  $type:
                        1=>'新订单通知',
                        2=>'发货通知（发给买家--货到付款）',
                        3=>'发货通知',
                $wxSdk->TemplateId($type);

                    $tp:
                        1=>'新订单通知买家',
                        2=>'新订单通知买家货到付款',
                        3=>'新订单通知卖家',
                        4=>'新订单通知卖家(货到付款)',
                        5=>'发货通知（发给买家--货到付款）',
                        6=>'发货通知，发给买家',
                        7=>'发货通知，发给卖家',
                $wxSdk->setTemplateData($tp,$data);
                */
//                    require_once(BASE_ROOT_PATH.'/weixin/framework/libraries/wxSdk.class.php');
//                    $wxSdk = new wxSdk();
//                    $model_order = Model('order');
//                    $wxSdk->TemplateId(1)->TemplateUrl(0)->setTemplateTopColor();
//                    $map['pay_sn'] = array('eq',$Notify->data['out_trade_no']);
//                    $new_order = $model_order->getOrderInfo($map,array('order_common','order_goods','store'));
//                    //循环产品发送消息
//                    foreach($new_order['extend_order_goods'] as $vv){
//                        $data = array(
//                            'goods_name' =>$vv['goods_name'],
//                            'goods_pay_price' =>$vv['goods_pay_price'],
//                            'goods_num' =>$vv['goods_num'],
//                            'profit' =>$vv['profit']//抵扣红包
//                        );
//                        $wxSdk->Touser(array('member_id'=>$vv['buyer_id']));
//                        $wxSdk->setTemplateData(1,$data);//新订单通知买家
//                        $wxSdk->sendTemplateMessage();
//
//                        //新订单发给卖家
//                        $wxSdk->Touser(array('member_id'=>$new_order['extend_store']['member_id']));
//                        $wxSdk->setTemplateData(3,$data);
//                        $wxSdk->sendTemplateMessage();
//
//                    }
                    $Notify->setReturnParameter('return_code', 'SUCCESS');//处理成功
                } else {
                    $Notify->setReturnParameter('return_code', 'FAIL');
                }
            } else {
                $Notify->setReturnParameter('return_code', 'SUCCESS');//已经处理过
            }

        } else {
            $Notify->setReturnParameter('return_code', 'FAIL');
            //数据错误
        }
        $returnXml = $Notify->returnXml();
        echo $returnXml;
    }

    /**
     * 获取支付接口实例
     */
    private function _get_payment_api()
    {
        $inc_file = BASE_PATH . DS . 'api' . DS . 'payment' . DS . $this->payment_code . DS . $this->payment_code . '.php';

        if (is_file($inc_file)) {
            require($inc_file);
        }

        $payment_api = new $this->payment_code();

        return $payment_api;
    }

    /**
     * 获取支付接口信息
     */
    private function _get_payment_config()
    {
        $model_mb_payment = Model('mb_payment');

        //读取接口配置信息
        $condition = array();
        $condition['payment_code'] = $this->payment_code;
        $payment_info = $model_mb_payment->getMbPaymentOpenInfo($condition);

        return $payment_info['payment_config'];
    }

    /**
     * 更新订单状态
     */
    private function _update_order($out_trade_no, $trade_no)
    {
        $model_order = Model('wx_order');
        $logic_payment = Logic('payment');

        $tmp = explode('|', $out_trade_no);
        $out_trade_no = $tmp[0];
        if (!empty($tmp[1])) {
            $order_type = $tmp[1];
        } else {
            $order_pay_info = Model('wx_order')->getOrderPayInfo(array('pay_sn' => $out_trade_no));
            if (empty($order_pay_info)) {
                $order_type = 'v';
            } else {
                $order_type = 'r';
            }
        }
        require_once(BASE_ROOT_PATH.'/weixin/framework/libraries/wxSdk.class.php');
        $wxSdk = new wxSdk();
        $wxSdk->TemplateId(1)->TemplateUrl(0)->setTemplateTopColor();

        if ($order_type == 'r') {
            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            //file_put_contents('result_u_r.txt',var_export($result,true));
            if (intval($result['data']['api_pay_state'])) {
                return array('state' => true);
            }
            $order_list = $result['data']['order_list'];
            $result = $logic_payment->updateRealOrder($out_trade_no, $this->payment_code, $order_list, $trade_no);



            $model_order = Model('order');
            $map['pay_sn'] = array('eq',$out_trade_no);
            $new_order = $model_order->getOrderInfo($map,array('order_common','order_goods','store'));
            //循环产品发送消息
            foreach($new_order['extend_order_goods'] as $vv){
                $data = array(
                    'goods_name' =>$vv['goods_name'],
                    'goods_pay_price' =>$vv['goods_pay_price'],
                    'goods_num' =>$vv['goods_num'],
                    'profit' =>$vv['profit']//抵扣红包
                );
                $wxSdk->Touser(array('member_id'=>$vv['buyer_id']));
                $wxSdk->setTemplateData(1,$data);//新订单通知买家
                $wxSdk->sendTemplateMessage();

                //新订单发给卖家
                $wxSdk->Touser(array('member_id'=>$new_order['extend_store']['member_id']));
                $wxSdk->setTemplateData(3,$data);
                $wxSdk->sendTemplateMessage();

            }
        } elseif ($order_type == 'v') {
            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            //file_put_contents('result_u_v.txt',var_export($result,true));
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                return array('state' => true);
            }
            $result = $logic_payment->updateVrOrder($out_trade_no, $this->payment_code, $result['data'], $trade_no);

            $model_vr_order = Model('vr_order');
            $map['pay_sn'] = array('eq',$out_trade_no);
            $new_order = $model_vr_order->getOrderList($map);
            //循环产品发送消息
            foreach($new_order as $vv){
                $data = array(
                    'goods_name' =>$vv['goods_name'],
                    'goods_pay_price' =>$vv['order_amount'],
                    'goods_num' =>$vv['goods_num'],
                    'profit' =>$vv['profit']//抵扣红包
                );
                $wxSdk->Touser(array('member_id'=>$vv['buyer_id']));
                $wxSdk->setTemplateData(1,$data);//新订单通知买家
                $wxSdk->sendTemplateMessage();

                //新订单发给卖家
                $store_member_id = Model('store')->getfby_store_id($vv['store_id'],'member_id');
                $wxSdk->Touser(array('member_id'=>$store_member_id));
                $wxSdk->setTemplateData(3,$data);
                $wxSdk->sendTemplateMessage();

            }


        }

        return $result;
    }

}
